package com.gooluke.shorten.strategy;

import com.gooluke.common.util.ExceptionUtil;
import com.gooluke.shorten.context.GenerateContext;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * 自定义短码生成策略
 */
@Component
public class CustomCodeStrategy implements ShortCodeStrategy {

    @Override
    public String generate(String originalUrl, GenerateContext context) {
        if (!StringUtils.hasLength(context.getCustomShortKey())) {
            ExceptionUtil.throwDefaultException("未提供自定义短码");
        }

        String code = context.getCustomShortKey();
        if (!code.matches("^[a-zA-Z0-9]{4,12}$")) {
            ExceptionUtil.throwDefaultException("短码格式错误");
        }

        return code.toLowerCase(); // 统一转为小写
    }

    @Override
    public boolean isCustom() {
        return true;
    }
}